package com.zq.learn.akka.typed;

import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.AbstractBehavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.Receive;

/**
 * 响应Actor
 *
 * @author ZhangQi
 * @date 2020/3/13
 */
public class GreeterBot extends AbstractBehavior<Greeter.Greeted> {
  //访问最大数
  private final int max;
  //访问次数
  private int greetingCounter;

  /**
   * 向外部提供创建方法
   * @param max
   * @return
   */
  public static Behavior<Greeter.Greeted> create(int max){
    return Behaviors.setup(context->new GreeterBot(context,max));
  }
  /**
   * 私有构造
   * @param context
   */
  private GreeterBot(ActorContext<Greeter.Greeted> context,int max) {
    super(context);
    this.max=max;
  }

  /**
   * 创建接收方法（重写）
   * @return
   */
  @Override public Receive<Greeter.Greeted> createReceive() {
    //处理消息
    return newReceiveBuilder().onMessage(Greeter.Greeted.class,this::onGreated).build();
  }

  /**
   * 返回问候处理
   * @param message
   * @return
   */
  private Behavior<Greeter.Greeted> onGreated(Greeter.Greeted message) {
    //累积问候次数
    greetingCounter++;
    getContext().getLog().info("Greeting {} for {}",greetingCounter,message.whom);
    //达到问候最大次数，停止
    if (greetingCounter==max){
      return Behaviors.stopped();
    }else {
      //否则，持续触发问候行为
      //推送消息
      message.from.tell(new Greeter.Greet(message.whom,getContext().getSelf()));
      return this;
    }
  }
}
